<?php

namespace app\api\controller;

use app\api\ApiBaseController;
use app\task\model\CategoryModel;
use app\task\model\OrderModel;
use app\task\model\TaskModel;
use app\task\model\TransportModel;
use think\Exception;
use think\facade\Db;

/**
 * 货运相关
 */
class Transport extends ApiBaseController
{
    /**
     * 不需要验证登录的接口
     * @var bool
     */
    public $noNeedLoginAuth = ['login', 'config'];

    /**
     * 商户信息
     */
    public function userInfo()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $user_info = array_keep(request()->merchant, [
            'nickname','avatar','phone','qq','email','expense','realname','company','id_company', 'is_verification'
        ]) ;
        $this->success('ok', $user_info);
    }

    /**
     * 配置数据
     */
    public function config()
    {
//        $merchant = request()->merchant;
//        if (empty($merchant)) $this->error('接口权限错误');

        $config['transport_type_list']  = explode('；', sysconf('transport_type_list')) ;
        $config['transport_scene_list']  = explode('；', sysconf('transport_scene_list'));
        $config['transport_distance_list']  = explode('；', sysconf('transport_distance_list'));

        $config['transport_scene_list_arr'] = get_transport_scene_list_arr();
        $config['transport_scene_list_obj'] = get_transport_scene_list_obj();

        $config['transport_distance_list_arr'] = get_transport_distance_list_arr();
        $config['transport_distance_list_obj'] = get_transport_distance_list_obj();

        $this->success('ok', $config);
    }

    /**
     * 发布运输任务
     */
    public function addTask()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');
        if (empty($merchant['phone'])) $this->error('请先登录');

        $input = $this->request->post();
        $data = [
            'category_id' => 1,
            'exec_at' => $input['exec_at'] ?? '',
            'name' => $input['name'] ?? '',
            'desc' => $input['desc'] ?? '',
            'require' => $input['require'] ?? '',
            'money' => floatval($input['money'] ?? 0),
            'province' => $input['province'] ?? '',
            'city' => $input['city'] ?? '',
            'area' => $input['area'] ?? '',
            'address' => $input['address'] ?? '',
            'file' => $input['file'] ?? '',
            'file_name' => $input['file_name'] ?? '',
            'lat' => $input['lat'] ?? 0,
            'lng' => $input['lng'] ?? 0,

            'is_company' => $input['is_company'] ?? 0,
        ];

        // 发单的商户
        $data['merchant_id'] = $merchant['id'];

        if (empty($data['category_id'])) $this->error('订单任务类型不能为空');
        $category = CategoryModel::where(['is_deleted'=>0, 'status'=>1])->where('id', $data['category_id'])->find();
        if (empty($category)) $this->error('订单任务类型不存在');

        if (empty($data['exec_at'])) $this->error('任务时间不能为空');
        if(strtotime($data['exec_at']) === false) $this->error('任务时间格式不正确');

//        if (empty($data['name'])) $this->error('请填写派单名称');

        if (empty($data['province']) || empty($data['city']) || empty($data['area'])) $this->error('任务地址地区不正确');

        if (empty($data['address'])) $this->error('任务地址不能为空');

//        if (empty($data['desc'])) $this->error('订单任务描述不能为空');

        if (empty($data['require'])) $this->error('订单要求不能为空');

        if (empty($data['money'])) $this->error('预估价格不能为空');
        if (floatval($data['money']) <= 0) $this->error('预估价格必须大于0');

//        if (empty($data['file'])) $this->error('审批文件不能为空');

        $data['place'] = $data['province'].$data['city'].$data['area'].$data['address'];

        $data['latlng'] = $data['lat'].','.$data['lng'];

        $data['task_status'] = TaskModel::TASK_STATUS__PENDING_REVIEW;

        // 验证货运数据
        $t_data = [
            'start_at' => $input['exec_at'] ?? '',
//            'end_at' => $input['end_at'] ?? '',
            'type' => $input['transport_type'] ?? '',
            'distance' => $input['transport_distance'] ?? '',
            'scene' => $input['transport_scene'] ?? '',
            'weight' => $input['weight'] ?? '',
            'province' => $input['province'] ?? '',
            'city' => $input['city'] ?? '',
            'area' => $input['area'] ?? '',
            'address' => $input['address'] ?? '',
            'lat' => $input['lat'] ?? '',
            'lng' => $input['lng'] ?? '',

            'province2' => $input['province2'] ?? '',
            'city2' => $input['city2'] ?? '',
            'area2' => $input['area2'] ?? '',
            'address2' => $input['address2'] ?? '',
            'lat2' => $input['lat2'] ?? '',
            'lng2' => $input['lng2'] ?? '',

            'type_other' => $input['transport_type_other'] ?? '',
            'scene_other' => $input['transport_scene_other'] ?? '',
        ];

//        if (empty($t_data['end_at'])) $this->error('订单结束时间不能为空');
//        if(strtotime($t_data['end_at']) === false) $this->error('订单结束时间格式不正确');

        if (empty($t_data['type'])) $this->error('货物种类不能为空');
        if (empty($t_data['distance'])) $this->error('运输距离不能为空');
        if (empty($t_data['scene'])) $this->error('货运场景不能为空');

        if (empty($t_data['weight'])) $this->error('预估重量不能为空');
        // 是否可以转换为整数的值
        if (filter_var($t_data['weight'], FILTER_VALIDATE_INT) === false) $this->error('预估重量格式不正确');
        $t_data['weight'] = intval($t_data['weight']);
        if ($t_data['weight'] > 1000000) $this->error('预估重量不大于1000000');

//        if (empty($t_data['province2']) || empty($t_data['city2']) || empty($t_data['area2'])) $this->error('订单任务地区不正确');
//
//        if (empty($t_data['address2'])) $this->error('订单任务详细地址不能为空');
//
//        if (strtotime($t_data['end_at']) <= strtotime($t_data['start_at'])){
//            $this->error('订单结束时间不能早于开始时间');
//        }

        Db::startTrans();
        try {
            $data['name'] = $t_data['type'];
            $task = TaskModel::create($data);
            // 写入关联的货运表
            $t_data['task_id'] = $task->id;
            $t_data['place'] = $task->place;
            $t_data['latlng'] = $task->latlng;
            $t_data['place2'] = $t_data['province2'].$t_data['city2'].$t_data['area2'].$t_data['address2'];
            $t_data['latlng2'] = $t_data['lat2'].','.$t_data['lng2'];;
            $transport = TransportModel::create($t_data);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('ok');
    }

    /**
     * 编辑任务
     */
    public function editTask()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');
        if (empty($merchant['phone'])) $this->error('请先登录');

        $input = $this->request->post();
        $data = [
            'id' => $input['id'] ?? 0,
            'category_id' => 1,
            'exec_at' => $input['exec_at'] ?? '',
            'name' => $input['name'] ?? '',
            'desc' => $input['desc'] ?? '',
            'require' => $input['require'] ?? '',
            'money' => floatval($input['money'] ?? 0),
            'province' => $input['province'] ?? '',
            'city' => $input['city'] ?? '',
            'area' => $input['area'] ?? '',
            'address' => $input['address'] ?? '',
            'file' => $input['file'] ?? '',
            'file_name' => $input['file_name'] ?? '',
            'lat' => $input['lat'] ?? 0,
            'lng' => $input['lng'] ?? 0,

            'is_company' => $input['is_company'] ?? 0,
        ];

        // 发单的商户
        $data['merchant_id'] = $merchant['id'];

        $task = TaskModel::where(['is_deleted'=>0, 'status'=>1])->where('merchant_id', $merchant['id'])->where('id', $data['id'])->find();
        if (empty($task)) $this->error('订单任务不存在');
        if ($task->task_status != TaskModel::TASK_STATUS__PENDING_REVIEW) $this->error('当前状态不允许编辑');

        if (empty($data['category_id'])) $this->error('订单任务类型不能为空');
        $category = CategoryModel::where(['is_deleted'=>0, 'status'=>1])->where('id', $data['category_id'])->find();
        if (empty($category)) $this->error('订单任务类型不存在');

        if (empty($data['exec_at'])) $this->error('任务时间不能为空');
        if(strtotime($data['exec_at']) === false) $this->error('任务时间格式不正确');

//        if (empty($data['name'])) $this->error('请填写派单名称');

        if (empty($data['province']) || empty($data['city']) || empty($data['area'])) $this->error('任务地区不正确');

        if (empty($data['address'])) $this->error('任务详细地址不能为空');

//        if (empty($data['desc'])) $this->error('订单任务描述不能为空');

        if (empty($data['require'])) $this->error('任务要求不能为空');

        if (empty($data['money'])) $this->error('预估价格不能为空');

//        if (empty($data['file'])) $this->error('审批文件不能为空');

        $data['place'] = $data['province'].$data['city'].$data['area'].$data['address'];

        $data['latlng'] = $data['lat'].','.$data['lng'];

        // 验证货运数据
        $t_data = [
            'start_at' => $input['exec_at'] ?? '',
//            'end_at' => $input['end_at'] ?? '',
            'type' => $input['transport_type'] ?? '',
            'distance' => $input['transport_distance'] ?? '',
            'scene' => $input['transport_scene'] ?? '',
            'weight' => $input['weight'] ?? '',
            'province' => $input['province'] ?? '',
            'city' => $input['city'] ?? '',
            'area' => $input['area'] ?? '',
            'address' => $input['address'] ?? '',
            'lat' => $input['lat'] ?? '',
            'lng' => $input['lng'] ?? '',

            'province2' => $input['province2'] ?? '',
            'city2' => $input['city2'] ?? '',
            'area2' => $input['area2'] ?? '',
            'address2' => $input['address2'] ?? '',
            'lat2' => $input['lat2'] ?? '',
            'lng2' => $input['lng2'] ?? '',

            'type_other' => $input['transport_type_other'] ?? '',
            'scene_other' => $input['transport_scene_other'] ?? '',
        ];

//        if (empty($t_data['end_at'])) $this->error('订单结束时间不能为空');
//        if(strtotime($t_data['end_at']) === false) $this->error('订单结束时间格式不正确');

        if (empty($t_data['type'])) $this->error('货运类型不能为空');
        if (empty($t_data['distance'])) $this->error('运输距离不能为空');
        if (empty($t_data['scene'])) $this->error('货运场景不能为空');

        if (empty($t_data['weight'])) $this->error('预估重量不能为空');
        // 是否可以转换为整数的值
        if (filter_var($t_data['weight'], FILTER_VALIDATE_INT) === false) $this->error('预估重量格式不正确');
        $t_data['weight'] = intval($t_data['weight']);
        if ($t_data['weight'] > 1000000) $this->error('预估重量不大于1000000');

//        if (empty($t_data['province2']) || empty($t_data['city2']) || empty($t_data['area2'])) $this->error('订单任务地区不正确');
//
//        if (empty($t_data['address2'])) $this->error('订单任务详细地址不能为空');
//
//        if (strtotime($t_data['end_at']) <= strtotime($t_data['start_at'])){
//            $this->error('订单结束时间不能早于开始时间');
//        }

        Db::startTrans();
        try {
            $data['name'] = $t_data['type'];
            $task = TaskModel::update($data);
            // 更新关联的货运表
            $transport = TransportModel::where('task_id', $task->id)->findOrEmpty();
            $t_data['task_id'] = $task->id;
            $t_data['place'] = $task->place;
            $t_data['latlng'] = $task->latlng;
            $t_data['place2'] = $t_data['province2'].$t_data['city2'].$t_data['area2'].$t_data['address2'];
            $t_data['latlng2'] = $t_data['lat2'].','.$t_data['lng2'];;
            $transport->save($t_data);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('ok');
    }

    /**
     * 订单任务列表（商家发布页面）
     */
    public function taskList()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $query = TaskModel::where(['is_deleted'=>0, 'status'=>1])->with(['category', 'transport'])
            ->field('id,name,exec_at,place,money,category_id,money,task_status')
            ->where('merchant_id', $merchant['id'])
            ->order('id desc');
        // 筛选项
        $task_status = $this->request->post('task_status', '');
        if (!empty($task_status)) $query->where('task_status', $task_status);
        $list = get_list($query);
        // 数据清洗
        foreach ($list['list'] as &$vo){
            $vo['exec_at'] = date('Y-m-d H:i', strtotime($vo['exec_at']));
            $vo['category'] = array_keep($vo['category'], ['id', 'name', 'img']);
            $vo['transport_type'] = $vo['transport']['type'] ?? '';
            $vo['transport_distance'] = $vo['transport']['distance'] ?? '';
            $vo['transport_scene'] = $vo['transport']['scene'] ?? '';
            $vo['weight'] = $vo['transport']['weight'] ?? '';
            unset($vo['transport']);
        }
        $this->success('ok', $list);
    }

    /**
     * 订单任务列表2（商家管理订单任务页面）
     */
    public function taskList2()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $query = TaskModel::alias('t')->where(['t.is_deleted'=>0, 't.status'=>1])->with(['category', 'task_order', 'transport'])
            ->field('t.*')
            ->join('task_order to', 'to.id = t.order_id', 'left')
            ->where('t.merchant_id', $merchant['id'])
            ->order('t.id desc');
        // 筛选项
        $type = $this->request->post('type', 0);
        if (empty($type)){
            $query->whereIn('t.task_status', [
                TaskModel::TASK_STATUS__PENDING_ACCEPTANCE,
                TaskModel::TASK_STATUS__PENDING_COMPLETION,
                TaskModel::TASK_STATUS__COMPLETED,
            ]);
        }else if ($type == 1){
            // 待接单
            $query->where('t.task_status', TaskModel::TASK_STATUS__PENDING_ACCEPTANCE)
                ->whereTime('t.exec_at', '>', date('Y-m-d H:i:s'));
        }else if ($type == 2){
            // 已接单未完成
            $query->where('t.task_status', TaskModel::TASK_STATUS__PENDING_COMPLETION)
                ->where('to.status', OrderModel::STATUS__PENDING_COMPLETION);
        }else if ($type == 3){
            // 飞手已经完成，等待商家审核
            $query->where('t.task_status', TaskModel::TASK_STATUS__PENDING_COMPLETION)
                ->where('to.status', OrderModel::STATUS__PENDING_REVIEW);
        }else if ($type == 4){
            // 已经过期的订单，且没人接单
            $query->whereIn('t.task_status', [
                TaskModel::TASK_STATUS__PENDING_ACCEPTANCE,
//                TaskModel::TASK_STATUS__PENDING_COMPLETION,
            ])
                ->whereTime('t.exec_at', '<', date('Y-m-d H:i:s'));
        }else{
            $this->error('type值错误');
        }
        $list = get_list($query);
        // 数据清洗
        foreach ($list['list'] as &$vo){
            $vo['is_expired'] = strtotime($vo['exec_at']) < time() ? 1 : 0;
            $vo['exec_at'] = date('Y-m-d H:i', strtotime($vo['exec_at']));
            $vo['category'] = array_keep($vo['category'], ['id', 'name', 'img']);
            $vo['transport_type'] = $vo['transport']['type'] ?? '';
            $vo['transport_distance'] = $vo['transport']['distance'] ?? '';
            $vo['transport_scene'] = $vo['transport']['scene'] ?? '';
            $vo['weight'] = $vo['transport']['weight'] ?? '';
            unset($vo['transport']);
        }
        $this->success('ok', $list);
    }

    /**
     * 订单任务详情（商家发布页面）
     */
    public function taskDetail()
    {
        $merchant = request()->merchant;
        if (empty($merchant)) $this->error('接口权限错误');

        $id = $this->request->post('id', 0);
        if (empty($id)) $this->error('ID不能为空');
        $task = TaskModel::where(['is_deleted'=>0, 'status'=>1])->with(['category', 'task_order', 'transport'])
            ->field('id,name,exec_at,place,money,category_id,money,desc,require,task_status,review_reason,order_id,province,city,area,address,file,lat,lng,file_name')
            ->where('merchant_id', $merchant['id'])
            ->where('id', $id)
            ->find();
        if (empty($task)) $this->error('订单任务不存在');
        $task = $task->toArray();
        $task['exec_at'] = date('Y-m-d H:i', strtotime($task['exec_at']));
        $task['category'] = array_keep($task['category'], ['id', 'name', 'img']);

        // 添加货运信息
        if($task['category_id'] == 1){
            $transport = $task['transport'];
            $task['start_at'] = date('Y-m-d H:i', strtotime($transport['start_at'] ?? ''));
            $task['end_at'] =  date('Y-m-d H:i', strtotime($transport['end_at'] ?? ''));
            $task['transport_type'] = $transport['type'] ?? '';
            $task['transport_scene'] = $transport['scene'] ?? '';
            $task['transport_distance'] = $transport['distance'] ?? '';
            $task['weight'] = $transport['weight'] ?? '';
            $task['province'] = $transport['province'] ?? '';
            $task['city'] = $transport['city'] ?? '';
            $task['area'] = $transport['area'] ?? '';
            $task['address'] = $transport['address'] ?? '';
            $task['place'] = $transport['place'] ?? '';
            $task['lat'] = $transport['lat'] ?? '';
            $task['lng'] = $transport['lng'] ?? '';
            $task['latlng'] = $transport['latlng'] ?? '';
            $task['province2'] = $transport['province2'] ?? '';
            $task['city2'] = $transport['city2'] ?? '';
            $task['area2'] = $transport['area2'] ?? '';
            $task['address2'] = $transport['address2'] ?? '';
            $task['place2'] = $transport['place2'] ?? '';
            $task['lat2'] = $transport['lat2'] ?? '';
            $task['lng2'] = $transport['lng2'] ?? '';
            $task['latlng2'] = $transport['latlng2'] ?? '';
            $task['transport_type_other'] = $transport['type_other'] ?? '';
            $task['transport_scene_other'] = $transport['scene_other'] ?? '';
        }
        $this->success('ok', $task);
    }
}